// src/pages/Search.jsx
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

import styles from "./index.module.css";
import { LeftOutline } from 'antd-mobile-icons'
import { Toast,Button } from "antd-mobile";
const FALLBACK_IMG = "https://via.placeholder.com/300x200?text=加载失败";

const HOT_KEYWORDS = ["iPhone", "二手车", "笔记本", "沙发", "电动车"];

export default function Search() {
  const navigate = useNavigate();
  const [keyword, setKeyword] = useState("");
  const [history, setHistory] = useState([]);
  const [recommend, setRecommend] = useState([]);

  // 控制标签的选中状态
  const [activeKeyword, setActiveKeyword] = useState("");
  const [hotactiveKeyword, sethotActiveKeyword] = useState("");
  // 加载历史记录
  useEffect(() => {
    const stored = JSON.parse(localStorage.getItem("search-history") || "[]");
    setHistory(stored);
  }, []);

  // 获取推荐数据
  useEffect(() => {
    const fetchRecommend = async () => {
      try {
        const res = await axios.get("http://127.0.0.1:3000/list");
        setRecommend(res.data.info || []);
      } catch (err) {
        console.error("推荐数据加载失败", err);
      }
    };
    fetchRecommend();
  }, []);

  const handleSearch = () => {
    if (!keyword.trim()) {
      Toast.show({ icon: "fail", content: "请输入关键词" });
      return;
    }

    // 存储历史
    const updated = [keyword, ...history.filter((k) => k !== keyword)].slice(0, 8);
    localStorage.setItem("search-history", JSON.stringify(updated));
    navigate('/result', { state: { keyword } })
  };

  const clearHistory = () => {
    localStorage.removeItem("search-history");
    setHistory([]);
  };

  return (
    <div style={{ padding: 12 }}>
      {/* 搜索框 */}
      <div style={{ display: "flex",      marginBottom: 12,alignItems:'center',justifyContent:'space-between'}}>
        <span onClick={()=>{navigate(-1)}}><LeftOutline /></span>
        <input
          value={keyword}
          onChange={(e) => setKeyword(e.target.value)}
          placeholder="请输入搜索内容"
          style={{
            flex: 0.9,
            padding: "8px 12px",
            borderRadius: 20,
            border: "1px solid #ccc",
          }}
        />
        <Button onClick={handleSearch} color='primary' style={{ marginLeft: 8 }}>
          搜索
        </Button>
      </div>

      {/* 历史记录 */}
      {history.length > 0 && (
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <strong>搜索历史</strong>
            <span onClick={clearHistory} style={{ color: "#999", cursor: "pointer" }}>
              清除
            </span>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
            {history.map((item, i) => (
              <span
                key={i}
                onClick={() => {setKeyword(item), setActiveKeyword(item)}}
                // style={{
                //   background: "#eee",
                //   padding: "4px 10px",
                //   borderRadius: 16,
                //   fontSize: 14,
                //   cursor: "pointer",
                // }}
                 className={`${styles.tag} ${activeKeyword === item ? styles.activeTag : ""}`}
              >
                {item}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 热门搜索 */}
      <div style={{ marginBottom: 20 }}>
        <strong>热门搜索</strong>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
          {HOT_KEYWORDS.map((item, i) => (
            <span
              key={i}
              onClick={() =>{setKeyword(item), sethotActiveKeyword(item) }}
              // style={{
              //   background: "#ffd",
              //   padding: "4px 10px",
              //   borderRadius: 16,
              //   fontSize: 14,
              //   cursor: "pointer",
              // }}
                className={`${styles.tag} ${hotactiveKeyword === item ? styles.activeTag : ""}`}
            >
              {item}
            </span>
          ))}
        </div>
      </div>

      {/* 推荐内容 */}
      {recommend.length > 0 && (
        <div>
          <strong>猜你喜欢</strong>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 12 }}>
            {recommend.map((item) => (
              <div
                key={item._id}
                onClick={() => navigate(`/detail/${item._id}`)}
                style={{
                  border: "1px solid #eee",
                  borderRadius: 8,
                  overflow: "hidden",
                  background: "#fafafa",
                }}
              >
                <img
                  src={item.img?.[0]?.url}
                  alt={item.title}
                  onError={(e) => (e.target.src = FALLBACK_IMG)}
                  style={{ width: "100%", height: 100, objectFit: "cover" }}
                />
                <div style={{ padding: "5px 8px" }}>
                  <div style={{ fontSize: 14, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {item.title}
                  </div>
                  <div style={{ color: "#f53f3f", fontWeight: "bold" }}>
                    ¥ {item.price || "面议"}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
